package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
@Slf4j
public class CacheClient {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void set(String key, Object value, Long time, TimeUnit unit){
        //需要把任意对象序列化为JSON字符串
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }
    public void setWithLogical(String key, Object value, Long time, TimeUnit unit){
        //设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));

        //需要把RedisData对象序列化为JSON字符串
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData),time,unit);
    }
    //解决缓存穿透问题
    //大量不存在的key，这个key对应的数据不存在，无论在redis缓存还是数据库中都不存在
    //会导致打大量无关的请求直接访问数据库，造成数据库持久层上的巨大压力

    public <R,ID> R queryWithPassThough(String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallback
        , Long time, TimeUnit unit){
        String key=keyPrefix+id;
        //1.从redis中查询商户缓存
        String Json = stringRedisTemplate.opsForValue().get(key);
        //2.判断商户是否存在
        if(StrUtil.isNotBlank(Json)){
            //3.存在，直接返回
            return JSONUtil.toBean(Json, type);
        }
        //判断命中是否是空值
        if(Json != null){
            return null;
        }
        //4.不存在，从数据库查询
        R r = dbFallback.apply(id);
        //5.不存在，返回错误
        if(r == null){
            //解决缓存穿透问题
            //将空值写入redis并设置过期时间
            stringRedisTemplate.opsForValue().set("cache:shop:" + id,"", RedisConstants.CACHE_NULL_TTL,
                    TimeUnit.MINUTES);
            return null;
        }
        //6.存在将商户信息写入redis
        this.set(key,r,time,unit);
        //7.返回
        return r;
    }
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    //互斥锁+逻辑过期解决缓存击穿问题
    public <R,ID> R queryWithLogicalExpire(String keyPrefix,ID id, Class<R> type, Function<ID,R> dbFallback
                                           , Long time, TimeUnit unit){
        //1.从redis中查询商户缓存
        String key=keyPrefix+id;
        String Json = stringRedisTemplate.opsForValue().get(key);
        //2.判断商户是否存在
        if(StrUtil.isBlank(Json)){
            //如果不存在
            return null;
        }
        //4.命中，需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(Json, RedisData.class);
        //5.判断是否过期
        LocalDateTime expireTime = redisData.getExpireTime();
        Object data = redisData.getData();
        JSONObject jsonObject = JSONUtil.parseObj(data);
        R r = JSONUtil.toBean(jsonObject, type);

        if(expireTime.isAfter(LocalDateTime.now())){
            //5.1未过期直接返回店铺信息
            return r;
        }
        //5.2已过期，需要缓存重建
        //6.缓存重建
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        //6.1 获取互斥锁
        boolean isLock = tryLock(lockKey);
        //6.2 判断是否获取成功
        if(isLock){
            //6.3 成功，开启一个独立线程实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                //重建缓存
                try {
                    R r1 = dbFallback.apply(id);
                    this.setWithLogical(keyPrefix,r1,time,unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }
        //6.4无论失败与否都会返回过期的商铺信息
        return r;
    }
    //获取锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    //释放锁
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }

}
